// Fill out your copyright notice in the Description page of Project Settings.


#include "JoinSessionButton.h"
#include "Components/TextBlock.h"
#include "MultiplayerSessions.h"
#include "MultiplayerSessionsSubsystem.h"
#include "OnlineSessionSettings.h"

void UJoinSessionButton::JoinSession()
{
	UE_LOG(MultiplayerSession, Warning, TEXT("UJoinSessionButton Button JoinSession!!!"));
	if (SessionResultObject)
	{
		if (UGameInstance* GameInstance = GetGameInstance())
		{
			if (auto MultiplayerSessionsSubsystem = GameInstance->GetSubsystem<UMultiplayerSessionsSubsystem>())
			{
				MultiplayerSessionsSubsystem->JoinSession(SessionResultObject->SessionSearchResult);
			}
		}
	}
	else
	{
		
		UE_LOG(MultiplayerSession, Warning, TEXT("UJoinSessionButton has no SessionResultObject!!!"));
	}
}

void UJoinSessionButton::NativeOnListItemObjectSet(UObject* ListItemObject)
{
	IUserObjectListEntry::NativeOnListItemObjectSet(ListItemObject);

	SessionResultObject = Cast<UUSessionResultObject>(ListItemObject);
	
	if (SessionResultObject)
	{
		auto Session = SessionResultObject->SessionSearchResult.Session;
		auto SessionSetting = Session.SessionSettings;
	
		FString SessionName;
		SessionSetting.Get(FName("SessionName"), SessionName);
	
		TextSessionName->SetText(FText::FromString(SessionName));
		// TextSessionOwner->SetText(FText::FromString(Session.OwningUserName));
		TextSessionOwner->SetText(FText::FromString(Session.OwningUserName + Session.GetSessionIdStr()));
		TextPlayerNumber->SetText(FText::FromString(FString::Printf(TEXT("%d/%d"),SessionSetting.NumPublicConnections - Session.NumOpenPublicConnections,SessionSetting.NumPublicConnections)));
	}
	else
	{
		UE_LOG(MultiplayerSession, Warning, TEXT("UJoinSessionButton Cast Failed!"));
	}
}
